package com.easemob.helpdesk.activity.transfer;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.easemob.helpdesk.AppConfig;
import com.easemob.helpdesk.activity.AlertDialog;
import com.easemob.helpdesk.activity.BaseActivityV2;
import com.easemob.helpdesk.adapter.AgentsAdapter;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DialogUtils;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.HDDataCallBack;
import com.hyphenate.kefusdk.chat.HDClient;
import com.hyphenate.kefusdk.entity.agent.AgentUser;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


/**
 * 会话转接界面，包含转接到客服和转接到技能组
 * <p/>
 */
public class TransferActivity extends BaseActivityV2  implements SwipeRefreshLayout.OnRefreshListener,AbsListView.OnScrollListener {

    /**
     * 跳转弹窗的REQUEST_CODE
     */
    private static final int REQUEST_CODE_ALERTDIALOG = 1;

    @Override
    protected void initFindView() {
        mBack=findViewById(R.id.back);

        mLeftimg=findViewById(R.id.leftimg);
        mSearchClear=findViewById(R.id.search_clear);
        mQuery=findViewById(R.id.query);
        mListview=findViewById(R.id.listview);

        mEmptyView=findViewById(R.id.emptyView);
        mSwipeLyAgent=findViewById(R.id.swipe_ly_agent);
        mBack.setOnClickListener(view -> finish());
        mSearchClear.setOnClickListener(view -> {
            mQuery.getText().clear();
        });

        mListview.setOnItemClickListener((adapterView, view, i, l) -> {
            mSelectedAgentUser = (AgentUser) adapterView.getItemAtPosition(i);
            startActivityForResult(
                    new Intent(TransferActivity.this, AlertDialog.class).putExtra("msg", "确定转接会话给<font color=\"#ED5600\">"+ mSelectedAgentUser.user.getNicename()+"</font>？"),
                    REQUEST_CODE_ALERTDIALOG);

        });

        mQuery.addTextChangedListener(new TextWatcher(){
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                mAdapter.getChatFilter().filter(s);
                if (s.length() > 0) {
                    mSearchClear.setVisibility(View.VISIBLE);
                } else {
                    mSearchClear.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    LinearLayout mBack;
    ImageView mLeftimg;
    ImageButton mSearchClear;
    EditText mQuery;
    ListView mListview;
    LinearLayout mEmptyView;
    SwipeRefreshLayout mSwipeLyAgent;


    /**
     * 客服列表数据
     */
    private List<AgentUser> mAgentUsers;
    /**
     * 列表适配器
     */
    private AgentsAdapter mAdapter;
    /**
     * 加载中的提示View
     */
    private Dialog mPd = null;
    /**
     * 选中的客服人员
     */
    private AgentUser mSelectedAgentUser;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppConfig.setFitWindowMode(this);
        setContentView(R.layout.activity_transfer);
        initFindView();
        init();
    }
    /**
     * 初始化View，并为View添加监听
     */
    private void init() {
        mAgentUsers = new ArrayList<>();
        mAdapter = new AgentsAdapter(this, mAgentUsers);

        mQuery.setHint("请输入姓名");
        mListview.setEmptyView(mEmptyView);
        mListview.setAdapter(mAdapter);
        mSwipeLyAgent.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_dark,
                R.color.holo_orange_light, R.color.holo_red_light);
        mSwipeLyAgent.setOnRefreshListener(this);
        mListview.setOnScrollListener(this);

        showLoading("加载中...");
        getAgentUserList();
    }

    private void showLoading(String msg){
        mPd = DialogUtils.getLoadingDialog(this, msg);
        mPd.show();
    }


    private void closeDialog() {
        if (mPd != null && mPd.isShowing()) {
            mPd.dismiss();
        }
        mPd = null;
    }


    private void getAgentUserList() {
        HDClient.getInstance().agentManager().getAgentList(false, new HDDataCallBack<List<AgentUser>>() {
            @Override
            public void onSuccess(final List<AgentUser> value) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    closeDialog();

                    mAgentUsers.clear();
                    for (AgentUser agentUser : value){
                        if (!"Offline".equals(agentUser.user.getOnLineState())){
                            mAgentUsers.add(agentUser);
                        }
                    }
                    Collections.sort(mAgentUsers, new Comparator<AgentUser>() {
                        @Override
                        public int compare(AgentUser lhs, AgentUser rhs) {
                            try {
                                String lState = lhs.user.getOnLineState();
                                String rState = rhs.user.getOnLineState();
                                int lIntState = CommonUtils.getAgentStatus(lState);
                                int rIntState = CommonUtils.getAgentStatus(rState);
                                return lIntState-rIntState;
                            }catch (Exception e){
                            }
                            return 0;
                        }
                    });
                    mAdapter.refresh();
                    mSwipeLyAgent.setRefreshing(false);
                }
            });
            }
            @Override
            public void onError(int error, String errorMsg) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeDialog();
                        Toast.makeText(TransferActivity.this, R.string.error_getAgentUserListFail,
                                Toast.LENGTH_SHORT).show();
                        mSwipeLyAgent.setRefreshing(false);
                    }
                });
            }
            @Override
            public void onAuthenticationException() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeDialog();
                        mSwipeLyAgent.setRefreshing(false);
                    }
                });
            }

        });

    }

/*
    @OnClick({R.id.back, R.id.search_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.search_clear:
                mQuery.getText().clear();
                break;
            default:
                break;
        }
    }*/

/*    @OnItemClick({R.id.listview})
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
        mSelectedAgentUser = (AgentUser) adapterView.getItemAtPosition(i);
        startActivityForResult(
                new Intent(this, AlertDialog.class).putExtra("msg", "确定转接会话给<font color=\"#ED5600\">"+ mSelectedAgentUser.user.getNicename()+"</font>？"),
                REQUEST_CODE_ALERTDIALOG);

    }*/

    @Override
    public void onRefresh() {
        getAgentUserList();
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        boolean enable;
        if (mListview != null && mListview.getChildCount() > 0) {
            //check if the first item of the list is visible
            boolean firstItemVisible = mListview.getFirstVisiblePosition() == 0;
            //check if the top of the first item is visible
            boolean topOfFirstItemVisible = mListview.getChildAt(0).getTop() == 0;
            //enabling or disabling the refresh layout
            enable = firstItemVisible && topOfFirstItemVisible;
            mSwipeLyAgent.setEnabled(enable);
        } else {
            mSwipeLyAgent.setEnabled(true);
        }
    }

/*    @OnTextChanged(value = {R.id.query})
    public void onTextChanged(CharSequence s, int start, int before, int count){
        mAdapter.getChatFilter().filter(s);
        if (s.length() > 0) {
            mSearchClear.setVisibility(View.VISIBLE);
        } else {
            mSearchClear.setVisibility(View.INVISIBLE);
        }
    }*/

    /**
     * 页面返回的回调
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        Intent数据
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_ALERTDIALOG) {
                String userId = mSelectedAgentUser.user.getUserId();
                Intent intent = new Intent();
                intent.putExtra("userId", userId);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDialog();
    }
}
